package com.uoko.common.thread;

import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 * CAS乐观自旋锁,性能很好,用于临界区操作。
 * </p>
 *
 * @author chenyingchun
 * Email qiaohai@uoko.com
 * created by 2018/6/6 0006
 */
public class SpinLock {

	private AtomicReference<Thread> sign = new AtomicReference<>();

	/***
	 * 锁
	 */
	public void lock() {
		Thread current = Thread.currentThread();
		while (!sign.compareAndSet(null, current)) {
		}
	}

	/**
	 * 解锁
	 */
	public void unlock() {
		Thread current = Thread.currentThread();
		sign.compareAndSet(current, null);
	}
}